﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using Newtonsoft.Json;

namespace Note_CHUSHI
{
    public class NoteBook
    {
        //笔记簿名称
        public string Name { get; set; }
        public string SecName { get; set; }

        //创建时间
        public DateTime CreatedTime { get; set; }

        //笔记簿路径
        public string DirectoryPath { get; private set; }
        private string Username { get; }



        public NoteBook(string username, string name)
        {
            Username = username;
            Name = name;
            SecName = name;
            CreatedTime = DateTime.Now;
        }

        public void Rename(string newName)
        {
            if (!string.IsNullOrWhiteSpace(newName))
            {
                Name = newName;
                // SecName保持不变，目录路径不受影响
            }
        }

        public void CreateDirectory(string rootDirectory)
        {
            var safeName = MakeValidDirectoryName(Name);
            DirectoryPath = Path.Combine(
                rootDirectory,
                $"{safeName}_{CreatedTime:yyyyMMddHHmmss}"
            );
            Directory.CreateDirectory(DirectoryPath);
        }

        public void Delete()
        {
            if (Directory.Exists(DirectoryPath))
            {
                Directory.Delete(DirectoryPath, true);
            }
        }

        public static NoteBook LoadFromDirectory(string directoryPath)
        {
            var metaPath = Path.Combine(directoryPath, "notebook.meta");
            var dirName = Path.GetFileName(directoryPath);

            // 解析用户名
            string username = Path.GetFileName(Path.GetDirectoryName(directoryPath));

            // 从目录名获取原始名称
            int underscoreIndex = dirName.LastIndexOf('_');
            string secName = dirName.Substring(0, underscoreIndex);

            var notebook = new NoteBook(username, secName)
            {
                DirectoryPath = directoryPath,
                CreatedTime = Directory.GetCreationTime(directoryPath)
            };

            // 加载元数据
            if (File.Exists(metaPath))
            {
                try
                {
                    var meta = JsonConvert.DeserializeAnonymousType(
                        File.ReadAllText(metaPath),
                        new { DisplayName = "", OriginalName = "", CreatedTime = DateTime.Now }
                    );
                    notebook.Name = meta.DisplayName;
                }
                catch { /* 忽略元数据加载错误 */ }
            }

            return notebook;
        }
       
        private string MakeValidDirectoryName(string name)
        {
            foreach (char c in Path.GetInvalidFileNameChars())
            {
                name = name.Replace(c, '_');
            }
            return name;
        }
    }
}
